package com.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;

@WebServlet("/SSHScheduleServlet")
public class SSHScheduleServlet extends HttpServlet {

	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String command = request.getParameter("command");

		Connection conn = new Connection("CentOS7", 22);
		conn.connect();

		boolean isAuth = conn.authenticateWithPassword("hadoop", "123456");
		if (isAuth == true) {
			Session session = conn.openSession();

			session.execCommand(command);

			// session.getStderr()
			BufferedReader br = new BufferedReader(new InputStreamReader(session.getStdout()));

			StringBuffer buffer = new StringBuffer(">" + command + "<br>");
			String line = null;
			while ((line = br.readLine()) != null) {
				System.out.println(line);
				buffer.append(line + "<br>");
			}

			session.close();
			br.close();

			request.setAttribute("msg", buffer.toString());
			request.getRequestDispatcher("/ssh-schedule.jsp").forward(request, response);
		}

		conn.close();
	}

}
